package com.zy.stock.crawl.impl;

import java.io.IOException;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.sun.media.sound.AlawCodec;
import com.zy.stock.crawl.CrawlService;
import com.zy.stock.domain.Stock;
import com.zy.stock.domain.StockCrawlRecord;
import com.zy.stock.mapper.StockCrawlRecordMapper;
import com.zy.stock.service.StockService;

@Component
@Transactional
public class CrawlServiceImpl implements CrawlService{
	
	private Logger logger = LoggerFactory.getLogger(CrawlServiceImpl.class);
	
	@Autowired
	private StockCrawlRecordMapper stockCrawlRecordMapper;
	
	@Autowired
	private StockService stockService;
	
	@Override
	public StockCrawlRecord crawl(Stock stock) throws Exception {
		// TODO Auto-generated method stub
		//创建HttpClientBuilder  
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
        //HttpClient  
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        
        String url = "http://gupiao.baidu.com/stock/";
        
        url = analyzeUrl(url,stock);
        
        HttpGet httpGet = new HttpGet(url);  
    
        httpGet.addHeader("Content-Type", "text/html;charset=UTF-8");  
        
        try {  
        	//执行get请求  
            HttpResponse httpResponse = closeableHttpClient.execute(httpGet);  
            //获取响应消息实体  
            HttpEntity entity = httpResponse.getEntity(); 

            Document doc = Jsoup.parse(EntityUtils.toString(entity,"UTF-8"));   
            
            StockCrawlRecord record = new StockCrawlRecord();
            record.setCode(stock.getCode());
            record.setName(stock.getName());
            record.setStockId(stock.getId());
            record.setCreateTime(new Date());
            
//            Elements stock_Div = doc.select(".op-sotckdynamic");
//            if(stock_Div.size()>0){
//            	Elements value_span = doc.select(".op-stockdynamic-cur > span");
//            	if(value_span.size()>0){
//            		//收盘价
//                    record.setTodayValue(new Double(value_span.get(0).text()));
//                    logger.info("收盘价 "+value_span.get(0).text());
//                    
//                    //状态
//                    Elements status_span = doc.select(".op-stockdynamic-update > span"); 
//                    if(status_span.size()>0){
//                    	record.setStatus(status_span.get(0).text());
//                    	logger.info("状态 "+status_span.get(0).text());
//                    }
//                    
//                    //抓取侧边栏七项目（今开、昨收、最高、最低、成交量、市盈率、每股收益）
//                    Elements values_li = doc.select(".op-stockdynamic-info > li"); 
//                    for(Element el:values_li){
//                    	analyzeValues(record, el);
//                    }
//                    logger.info(JSONObject.toJSONString(record));
//                    stockCrawlRecordMapper.save(record);
//            	}else{
//            		value_span = doc.select(".op-stockdynamic-moretab-cur > span");
//            		if(value_span.size()>0){
//                		//收盘价
//                        record.setTodayValue(new Double(value_span.get(0).text()));
//                        logger.info("收盘价 "+value_span.get(0).text());
//                        
//                        //状态
//                        Elements status_span = doc.select(".op-stockdynamic-moretab-update > span"); 
//                        if(status_span.size()>0){
//                        	record.setStatus(status_span.get(0).text());
//                        	logger.info("状态 "+status_span.get(0).text());
//                        }
//                        
//                        //抓取侧边栏七项目（今开、昨收、最高、最低、成交量、市盈率、每股收益）
//                        Elements values_li = doc.select(".op-stockdynamic-moretab-info > li"); 
//                        for(Element el:values_li){
//                        	analyzeValues(record, el);
//                        }
//                        logger.info(JSONObject.toJSONString(record));
//                        stockCrawlRecordMapper.save(record);
//                	}
//            	}
//            }
            
            //抓取状态
            Elements stockBets_div = doc.select("div.stock-bets");
            Elements state_span = stockBets_div.select("span");
            if(state_span.size()>0){
                logger.info("抓取股票状态..."+state_span.get(1).text());
                record.setStatus(state_span.get(1).text());
                stock.setCrawlStatus(state_span.get(1).text());
            }
            //抓取当前价格
            Elements value_strong = stockBets_div.select("strong");
            if(value_strong.size()>0){
            	logger.info("抓取股票价格..."+value_strong.get(0).text());
            	record.setTodayValue(new Double(value_strong.get(0).text()));
            	stock.setValue(new Double(value_strong.get(0).text()));
            	stockService.update(stock);
            }
            
            //抓取其他明细数据
            Elements contents = doc.select("div.bets-content");
            Elements dls = contents.select("dl");
            for(Element dl:dls){
            	analyzeValues(record, dl);
            }
            
            logger.info(JSONObject.toJSONString(record));
            stockCrawlRecordMapper.save(record);
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
            	//关闭流并释放资源  
            	closeableHttpClient.close();  
            } catch (IOException e) {  
            	e.printStackTrace();  
            }  
        }
		return null;
	}
	
	private void analyzeValues(StockCrawlRecord record,Element element){
		try {
			Elements spans = element.select("dt");
			Elements values = element.select("dd");
			if(spans.size()>0){
				String name = spans.get(0).text();
				if(name.equalsIgnoreCase("今开")){
					record.setBeginValue(new Double(values.get(0).text()));
				}
				if(name.equalsIgnoreCase("昨收")){
					record.setLastDayValue(new Double(values.get(0).text()));
				}
				if(name.equalsIgnoreCase("最高")){
					record.setBiggestValue(new Double(values.get(0).text()));
				}
				if(name.equalsIgnoreCase("最低")){
					record.setLastValue(new Double(values.get(0).text()));
				}
				if(name.equalsIgnoreCase("成交量")){
					record.setDealNum(values.get(0).text());
				}
				if(name.indexOf("市盈率")>-1){
					record.setPeRatio(values.get(0).text());
				}
				if(name.equalsIgnoreCase("每股收益")){
					record.setEarnings(new Double(values.get(0).text()));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage());
		}		
	}
	
	private String analyzeUrl(String url,Stock stock){
		String code = stock.getCode();
		char[] code_arr = code.toCharArray();
		if(code_arr[0]=='6'){
			url=url+"sh"+code+".html";
		}else{
			url=url+"sz"+code+".html";
			logger.info(url);
		}
		return url;
	}
}
